package com.dai.rpc.netty;

import com.dai.rpc.config.MyRpcConfig;
import com.dai.rpc.netty.handler.MyRpcThreadFactory;
import com.dai.rpc.netty.handler.NettyServerInitiator;
import com.dai.rpc.server.MyServiceProvider;
import com.dai.rpc.util.RuntimeUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultEventExecutorGroup;

public class NettyServer implements MyService {

    private EventLoopGroup bossGroup;
    private EventLoopGroup workGroup;
    private MyServiceProvider myServiceProvider;
    private DefaultEventExecutorGroup eventExecutors;
    private boolean isRunning;
    private MyRpcConfig myRpcConfig;


    @Override
    public void run() {
        try{
            bossGroup = new NioEventLoopGroup();
            workGroup = new NioEventLoopGroup();
            // 启动类
            ServerBootstrap b =  new ServerBootstrap();
            eventExecutors =  new DefaultEventExecutorGroup(RuntimeUtil.cpus() * 2,new MyRpcThreadFactory(myServiceProvider));
            b.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    // TCP默认开启了 Nagle 算法，该算法的作用是尽可能的发送大数据快，减少网络传输。TCP_NODELAY 参数的作用就是控制是否启用 Nagle 算法。
                    .childOption(ChannelOption.TCP_NODELAY,true)
                    // 是否开启 TCP 底层心跳机制
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    // 表示系统用于临时存放已完成三次握手的请求的队列的最大长度,如果连接建立频繁，服务器处理创建新连接较慢，可以适当调大这个参数
                    .childOption(ChannelOption.SO_BACKLOG,1024)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    // 当客户端第一次进行请求的时候才会进行初始化
                    .childHandler(new NettyServerInitiator(eventExecutors));
            // 绑定端口

            b.bind(myRpcConfig.getProviderPort()).sync().channel();
            isRunning = true;
            Runtime.getRuntime().addShutdownHook(new Thread(){
                @Override
                public void run() {
                    stopNettyServer();
                }
            });
        }catch (Exception e){
            e.printStackTrace();
            isRunning = false;
        }
    }

    @Override
    public void stop() {
        stopNettyServer();
    }

    private void stopNettyServer() {

        isRunning = false;
        if(eventExecutors != null) eventExecutors.shutdownGracefully();
        if(bossGroup != null) bossGroup.shutdownGracefully();
        if(workGroup != null) workGroup.shutdownGracefully();
    }

    public void setMyServiceProvider(MyServiceProvider myServiceProvider) {
        this.myServiceProvider = myServiceProvider;
    }



    public boolean isRunning() {
        return isRunning;
    }

    public void init(MyRpcConfig myRpcConfig){
        this.myRpcConfig = myRpcConfig;
    }
}
